package com.usian.service;

import com.usian.mapper.TbItemCatMapper;
import com.usian.pojo.TbItemCat;
import com.usian.pojo.TbItemCatExample;
import com.usian.redis.RedisClient;
import com.usian.utils.CatNode;
import com.usian.utils.CatResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ItemCatServiceImpl implements ItemCatService {
    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    @Autowired
    private RedisClient redisClient;

    @Value("${PROTAL_CATRESULT_KEY}")
    private String PROTAL_CATRESULT_KEY;

    /**
     * 类目查询
     * 薛丁豪22.3.23
     *
     * @param id
     * @return
     */
    @Override
    public List<TbItemCat> selectItemCategoryByParentId(Long id) {
        TbItemCatExample tbItemCatExample = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = tbItemCatExample.createCriteria();
        criteria.andParentIdEqualTo(id);
//        criteria.andStatusEqualTo(1);
//        if (id != 0) {
//            int a = 6 / 0;
//        }
        return tbItemCatMapper.selectByExample(tbItemCatExample);
    }

    /**
     * 薛丁豪左侧类目菜单
     * shangxingming缓存商品分类菜单
     * 22.03.25
     * @return
     */
    @Override
    public CatResult selectItemCategoryAll() {
        CatResult catResult = (CatResult) redisClient.get(PROTAL_CATRESULT_KEY);
        if (catResult != null && catResult.getData() != null){
            return catResult;
        }
        catResult = new CatResult();
        catResult.setData(getCatList(0L));
        redisClient.set(PROTAL_CATRESULT_KEY,catResult);
        return catResult;
    }

    private List<?> getCatList(Long parentId){
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria =example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        List<TbItemCat> list = this.tbItemCatMapper.selectByExample(example);
        List resultList = new ArrayList<>();
        int count = 0;
        for(TbItemCat tbItemCat:list){
            //判断父节点
            CatNode catNode = new CatNode();
            catNode.setName(tbItemCat.getName());
            //判断子节点
            catNode.setItem(getCatList(tbItemCat.getId()));
            resultList.add(catNode);
            count++;
            if(count==18){
                break;
            }else {
                resultList.add(tbItemCat.getName());
            }
        }
        return resultList;
    }
}
